package epin.fujiajun.data.array;

import epin.fujiajun.data.Array;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by DELL on 2017/8/15.
 */
public class Date extends Array<Date> {

    private final int day;
    private final int month;
    private final int year;

    public Date(int year, int month, int day) {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public int getYear() {
        return year;
    }

    public int getDay() {
        return day;
    }

    public int getMonth() {
        return month;
    }

    @Override
    public int compareTo(Date o) {
        if (this.year > o.year) return +1;
        if (this.year < o.year) return -1;
        if (this.month > o.month) return +1;
        if (this.month < o.month) return -1;
        if (this.day > o.day) return +1;
        if (this.day < o.day) return -1;
        return 0;
    }

    @Override
    public String toString() {
        return year + "-" + month + "-" + day;
    }

    public static Date[] createArray(int size, String beginDate, String endDate){
        Date[] a = new Date[size];

        for (int i = 0; i < size; i++){
            java.util.Date date = randomDate(beginDate, endDate);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            a[i] = new Date(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH));
        }

        return a;
    }

    private static java.util.Date randomDate(String beginDate, String endDate){
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date begin = format.parse(beginDate);
            java.util.Date end = format.parse(endDate);

            if (begin.getTime() < end.getTime()){
                long date = random(begin.getTime(), end.getTime());

                return new java.util.Date(date);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static long random(long begin, long end) {
        long rtn = begin + (long) (Math.random() * (end - begin));
        // 如果返回的是开始时间和结束时间，则递归调用本函数查找随机值
        if (rtn == begin || rtn == end) {
            return random(begin, end);
        }
        return rtn;
    }

}
